package com.YxyBackMange.Controller.SystemController;


import com.YxyBackMange.Constant.SysConstant;
import com.YxyBackMange.Dto.Message;
import com.YxyBackMange.Entity.Sys.SysMenu;
import com.YxyBackMange.Entity.Sys.SysRole;
import com.YxyBackMange.Entity.Sys.SysUser;
import com.YxyBackMange.Mapper.Sys.SysMenuMapper;
import com.YxyBackMange.Mapper.Sys.SysRoleMapper;
import com.YxyBackMange.Util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
public class SystemController {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 设置欢迎页面
     *
     * @return
     */
    @RequestMapping("/")
    public String index() {
        return "/Web/WebGoodsInfo/findAllGoodsInfo";
    }

    /**
     * 验证码
     *
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/Admin/System/imgValidateCode")
    public String getSysManageLoginCode(HttpServletResponse response, HttpServletRequest request) {
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");//设置HttpOnly属性,防止Xss攻击
        response.setDateHeader("Expire", 0);
        try {
            String code = VerifyCodeUtils.outputVerifyImage(80, 30, response.getOutputStream(), 4);
            request.getSession(true).setAttribute(SysConstant.IDENTIFY_CODE_MARK, code.toLowerCase());
            return "";
        } catch (Exception e) {
            return "error";
        }

    }

    /**
     * 用户登录
     *
     * @param identity
     * @param token
     * @param rememberMe
     * @param session
     * @return
     */
    @RequestMapping("/Admin/System/userLogin")
    public String loginUser(String identity, String token, String identifyCode, boolean rememberMe, HttpSession session, ModelMap map) {
        Message msg = new Message();
        Integer loginCount = (Integer) session.getAttribute(SysConstant.LOGIN_FAILED_NUMBER_MARK);
        String identifyCodeIsOpen = (String) session.getAttribute(SysConstant.IDENTIFY_CODE_OPEN);
        String sessionIdentifyCode = (String) session.getAttribute(SysConstant.IDENTIFY_CODE_MARK);
        if (identifyCodeIsOpen != null && identifyCodeIsOpen.equals("YES")) {
            System.out.println("已经开启验证码");
            if (identifyCode == null || !sessionIdentifyCode.equals(identifyCode.toLowerCase())) {
                System.out.println("输入的验证码:" + identifyCode);
                System.out.println("输入的验证码：" + sessionIdentifyCode);
                msg.setMsg("验证码错误，请输入正确的验证码?");
                map.put("msg", msg);
                return "/admin/login.jsp";//返回登录页面
            }
        }
        if (loginCount == null) {
            loginCount = 1;
        }

        if (loginCount > 5) {
            msg.setMsg("登录次数过多,请30分钟以后重试!");
            map.put("msg", msg);
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(identity, token, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            usernamePasswordToken.setRememberMe(rememberMe);
            SysUser sysUser = (SysUser) subject.getPrincipal();
            session.setAttribute(SysConstant.USER_IDENTIFICATION, sysUser);
            session.setAttribute(SysConstant.LOGIN_FAILED_NUMBER_MARK, 0);
            return "redirect:/Admin/System/home";
        } catch (Exception e) {
            msg.setMsg("登录失败,账号或密码错误!");
            map.put("msg", msg);
            session.setAttribute(SysConstant.LOGIN_FAILED_NUMBER_MARK, loginCount + 1);
            session.setAttribute(SysConstant.IDENTIFY_CODE_OPEN, "YES");
            e.printStackTrace();
            return "/admin/login.jsp";//返回登录页面
        }

    }

    @RequestMapping("/Admin/System/loginOut")
    public String loginOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/admin/login.jsp";
    }

    @RequestMapping("/Admin/System/home")
    public String home(HttpSession session, ModelMap modelMap) {
        Set<SysMenu> menuSet = new HashSet<SysMenu>();
        SysUser user = (SysUser) session.getAttribute(SysConstant.USER_IDENTIFICATION);
        if (user == null) {
            System.out.println("用户信息为空");
            return "/admin/login.jsp";
        }
        List<SysRole> roleList = sysRoleMapper.selectSysRoleByUserId(user.getId());
        for (SysRole sysRole : roleList) {
            List<SysMenu> list = sysMenuMapper.selectSysMenuByRoleId(sysRole.getId());
            System.out.println(list);
            menuSet.addAll(list);
        }

        modelMap.put("menuList", menuSet);
        modelMap.put("sysUser", user);
        return "/admin/index.jsp";

    }
}
